package com.neu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.neu.base.PageBean;
import com.neu.base.Result;
import com.neu.entity.Project;
import com.neu.entity.ProjectUserRole;
import com.neu.entity.Tenant;

import com.neu.entity.User;
import com.neu.entity.security.LoginUser;
import com.neu.mapper.TenantMapper;
import com.neu.mapper.UserMapper;
import com.neu.service.ProjectService;
import com.neu.service.ProjectUserRoleService;
import com.neu.service.TenantService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageBean<Tenant> pagelist(Integer pageNum, Integer pageSize) {
        Page<Tenant> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tenant::getDelFlag, "1");// 查询未删除的租户

        //根据当前登录用户的权限查询通知
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();

        if (!permissions.contains("ROLE_super")) {
            queryWrapper.eq(Tenant::getTenantId, loginUser.getTenantId());
        }

        Page<Tenant> tenantPage = this.baseMapper.selectPage(page, queryWrapper);
        return new PageBean<>(tenantPage);
    }

    @Override
    public PageBean<Tenant> search(Map map) {
        Integer pageNum = (Integer) map.get("pageNum");
        Integer pageSize = (Integer) map.get("pageSize");

        // 获取嵌套的 search Map
        Map<String, Object> searchMap = (Map<String, Object>) map.get("search");
        //{pageNum=1, pageSize=10, search={username=, phone=, status=1, createTimeList=[2024-10-27T16:00:00.000Z, 2024-11-03T16:00:00.000Z], deptIdList=[1842128938393600002, 1842128590274756609]}}

        // 从 search Map 中获取值
        String tenantId = (String) searchMap.get("tenantId");
        String tenantName = (String) searchMap.get("tenantName");
        String contactId = (String) searchMap.get("contactId");
        String rights = (String) searchMap.get("rights");
        List<String> expireTimeList = (List<String>) searchMap.get("expireTimeList");
        List<String> createTimeList = (List<String>) searchMap.get("createTimeList");

        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
        //根据当前登录用户的权限查询
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();

        if (StringUtils.hasText(tenantName) && !permissions.contains("ROLE_super") && !loginUser.getTenantName().contains(tenantName)) {
            return new PageBean<>(new Page<>());
        }
        if (StringUtils.hasText(tenantId) && !permissions.contains("ROLE_super") && !tenantId.equals(loginUser.getTenantId())) {
            return new PageBean<>(new Page<>());
        }
        if (!permissions.contains("ROLE_super")) {
            queryWrapper.eq(Tenant::getTenantId, loginUser.getTenantId());
        }

        //expireTimeList
        //把日期字符串转换为日期对象
        LocalDateTime startTimeExpire = null;
        LocalDateTime endTimeExpire = null;
        if (expireTimeList != null && expireTimeList.size() == 2) {
            //OffsetDateTime适用于解析带有 "Z" 的日期字符串。
            startTimeExpire = OffsetDateTime.parse(expireTimeList.get(0), DateTimeFormatter.ISO_OFFSET_DATE_TIME).toLocalDateTime();
            endTimeExpire = OffsetDateTime.parse(expireTimeList.get(1), DateTimeFormatter.ISO_OFFSET_DATE_TIME).toLocalDateTime();
        }
        //createTimeList
        LocalDateTime startTimeCreate = null;
        LocalDateTime endTimeCreate = null;
        if (createTimeList != null && createTimeList.size() == 2) {
            //OffsetDateTime适用于解析带有 "Z" 的日期字符串。
            startTimeCreate = OffsetDateTime.parse(createTimeList.get(0), DateTimeFormatter.ISO_OFFSET_DATE_TIME).toLocalDateTime();
            endTimeCreate = OffsetDateTime.parse(createTimeList.get(1), DateTimeFormatter.ISO_OFFSET_DATE_TIME).toLocalDateTime();
        }

        Page<Tenant> page = new Page<>(pageNum, pageSize);

        queryWrapper.eq(StringUtils.hasText(tenantId), Tenant::getTenantId, tenantId)
                .like(StringUtils.hasText(tenantName), Tenant::getTenantName, tenantName)
                .eq(StringUtils.hasText(contactId), Tenant::getContactId, contactId)
                .eq(StringUtils.hasText(rights), Tenant::getRights, rights)
                .between(expireTimeList != null && expireTimeList.size() == 2, Tenant::getExpireTime, startTimeExpire, endTimeExpire)
                .between(createTimeList != null && createTimeList.size() == 2, Tenant::getCreateTime, startTimeCreate, endTimeCreate);

        Page<Tenant> tenantIPage = tenantMapper.selectPage(page, queryWrapper);

        return new PageBean<>(tenantIPage);
    }

    @Override
    public List<String> contactIds() {
        // 创建 LambdaQueryWrapper
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        // 选择 userId 字段
        queryWrapper.select(User::getUserId);

        // 执行查询并获取结果
        List<User> userList = userMapper.selectList(queryWrapper);

        // 提取 userId 并返回
        return userList.stream()
                .map(User::getUserId) // 提取 userId
                .collect(Collectors.toList()); // 收集到 List<String>
    }

    @Override
    public List<Tenant> all() {
        LambdaQueryWrapper<Tenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Tenant::getDelFlag, "1");// 查询未删除的用户

        //根据当前登录用户的权限查询
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        List<String> permissions = loginUser.getAuthorityStrings();

        if (!permissions.contains("ROLE_super")) {
            queryWrapper.eq(Tenant::getTenantId, loginUser.getTenantId());
        }
        return this.list(queryWrapper);
    }

    @Override
    public Result removeTenant(String tenantId) {
        //判断该租户下是否有用户
       List<User> userList= userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getTenantId,tenantId));
       if(userList.size()>0) {
           return Result.error("该租户下有用户，不能删除");
       }
        this.removeById(tenantId);
        return Result.success();
    }

    @Override
    public Result removeTenantBatch(List<String> tenentIdList) {
        for (String s : tenentIdList) {
            //判断该租户下是否有用户
            List<User> userList= userMapper.selectList(new LambdaQueryWrapper<User>().eq(User::getTenantId,s));
            Tenant tenant = this.getById(s);
            if(!userList.isEmpty()) {
                return Result.error("该"+tenant.getTenantName()+"租户下有用户，不能删除");
            }
        }

        return Result.success(this.removeByIds(tenentIdList));
    }

    public boolean process(List<Tenant> tenantList) {
        // 这里可以添加数据验证逻辑
        // 例如，检查必填字段是否为空，数据格式是否正确等
        for (Tenant tenant : tenantList) {
            if (tenant.getTenantId() == null || tenant.getTenantId().trim().isEmpty()) {
                //抛出自定义异常，交给全局异常处理器处理，而不是被 Spring Security 捕获。使其不属于 Spring Security 处理的范围。

                // throw new BusinessException("id不能为空");
                return false;
            }
            if (tenant.getTenantName() == null || tenant.getTenantName().trim().isEmpty()) {
                //throw new BusinessException("名称不能为空");
                return false;
            }

        }
        // 保存数据到数据库
        this.saveBatch(tenantList);
        return true;
    }

}
